package com.example.planetexploder.model.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.example.planetexploder.bean.maindata.ImgInfo;
import com.example.planetexploder.constants.LogConst;

import java.util.ArrayList;

/**
 * 图片组表操作集
 * @author 宋熙然
 * 修改日期：2019.10.27
 * 测试完毕
 */
public class ImgGroupTable {

    private final DBHelper helper;

    public ImgGroupTable(Context context) {
        helper = new DBHelper(context);
        helper.getWritableDatabase();
    }

    /**
     * 创建图片组表
     * @param imgGroupId 图片组表id
     */
    public void create_ImgGroupTable(String imgGroupId) {
        Log.d(LogConst.MTAG, "create_ImgGroupTable()");
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "CREATE TABLE " + imgGroupId + ImgInfo.IMGTABLE_HEADER;
        db.execSQL(sql);
        db.close();
    }

    /**
     * 删除图片组表
     * @param imgGroupId 图片组表id
     */
    public void delete_ImgGroupTable(String imgGroupId) {
        Log.d(LogConst.MTAG, "delete_ImgGroupTable()");
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "DROP TABLE " + imgGroupId + ";";
        db.execSQL(sql);
        db.close();
    }

    /**
     * 向图片组表中添加图片信息
     * @param imgInfo 图片信息
     */
    public void add_ImgInfo_To_ImgGroupTable(String ImgGroupId, ImgInfo imgInfo) {
        Log.d(LogConst.MTAG, "add_ImgInfo_To_ImgGroupTable()");
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(ImgInfo.IMGTABLE_IMG_ID, imgInfo.imgId);
        db.insert(ImgGroupId, null, cv);
        db.close();
    }

    /**
     * 从图片组表中删除信息
     * @param imgId 图片id
     */
    public void delete_ImgInfo_From_ImgGroupTable(String ImgGroupId, String imgId) {
        Log.d(LogConst.MTAG, "delete_ImgInfo_From_ImgGroupTable()");
        SQLiteDatabase db = helper.getWritableDatabase();
        String sql = "DELETE FROM " + ImgGroupId + " WHERE " + ImgInfo.IMGTABLE_IMG_ID + " = ?;";
        db.execSQL(sql, new Object[]{imgId});
        db.close();
    }

    /**
     * 获得图片组表中的所有信息
     * @param imgGroupId 图片组表id
     * @return 图片组表中的所有信息
     */
    public ArrayList<ImgInfo> get_ImgGroupTable(String imgGroupId) {
        Log.d(LogConst.MTAG, "get_ImgGroupTable()");
        ArrayList<ImgInfo> list = new ArrayList<>();
        SQLiteDatabase db = helper.getReadableDatabase();

        Cursor c = db.query(imgGroupId, null, null, null, null, null, null);
        while (c.moveToNext()){
            ImgInfo imgInfo = new ImgInfo();
            imgInfo.imgId = c.getString(c.getColumnIndex(ImgInfo.IMGTABLE_IMG_ID));
            list.add(imgInfo);
        }

        c.close();
        db.close();
        return list;
    }

}
